package com.wolfking.converter.transform.base;


import com.wolfking.converter.transform.FieldTransform;
import lombok.extern.slf4j.Slf4j;

import java.math.BigInteger;
import java.util.regex.Pattern;

@Slf4j
public class BigIntegerFieldTransform implements FieldTransform<BigInteger> {

    private final Pattern pattern = Pattern.compile("[0-9]*");

    @Override
    public boolean canTransform(Class<?> fieldType) {
        return fieldType.equals(BigInteger.class);
    }

    @Override
    public BigInteger transform(Object value) {
        String toString = value.toString();
        if (Number.class.isAssignableFrom(value.getClass()) || pattern.matcher(toString).matches()) {
            return new BigInteger(toString);
        }
        try {
            return new BigInteger(toString);
        } catch (Exception e) {
            log.debug("", e);
        }
        throw new IllegalStateException(String.format("BigInteger[%s]换换异常", value.toString()));
    }
}
